package com.lfk.justweengine;

import com.lfk.justweengine.Anim.FrameAnimation;
import com.lfk.justweengine.Anim.MoveAnimation;
import com.lfk.justweengine.Anim.VelocityAnimation;
import com.lfk.justweengine.Engine.*;
import com.lfk.justweengine.Info.UIdefaultData;
import com.lfk.justweengine.Sprite.BaseSprite;
import com.lfk.justweengine.Sprite.BaseSub;
import com.lfk.justweengine.Sprite.FrameType;
import com.lfk.justweengine.Utils.music.MusicPlayer;
import com.lfk.justweengine.Utils.music.SoundManager;
import com.lfk.justweengine.Utils.script.Float2;
import com.lfk.justweengine.Utils.script.Float3;
import com.lfk.justweengine.Utils.tools.PaintView;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.utils.Rect;
import ohos.agp.utils.RectFloat;
import ohos.bundle.AbilityInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

public class MainAbility extends Engine implements Runnable, Component.TouchEventListener, Component.DrawTask {

    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x0, MainAbility.class.getSimpleName());
    private MusicPlayer player;
    private SurfaceProvider e_surfaceView;
    private SurfaceProvider e_videoSurfaceProvider;
    private DependentLayout e_surfaceViewLayout;
    private Canvas e_canvas;
    // 主循环
    private Thread e_thread;
    // 循环控制
    private boolean e_running, e_paused;
    private int e_pauseCount;
    private Paint e_paintDraw, e_paintFont;
    private int e_numPoints;
    private long e_prefferredFrameRate, e_sleepTime;
    private Point[] e_touchPoints;
    private boolean e_touchModesAble;
    // 多点触控数
    private int e_touchNum;
    private int e_backgroundColor;
    private boolean e_isFrameOpen;
    private TouchMode e_touch_Mode;
    private CopyOnWriteArrayList<BaseSub> e_sprite_group;
    private CopyOnWriteArrayList<BaseSub> e_spirte_recycle_group;
    private boolean firstKeyDown = false;

    GameTextPrinter printer;
    Paint paint;
    Canvas canvas;
    GameTimer timer, shoottimer, enemyTimer;
    PixelMap backGround2X;
    BaseSprite ship;
    float startX, startY, offsetX, offsetY;
    RectFloat bg_src;
    RectFloat bg_dst;
    Point bg_scroll;
    GameTexture shoot;
    GameTexture enemyPic;
    Random random;
    final int SHIP = 0;
    final int BULLET = 1;
    final int ENEMY = 2;
    int enemyNum = 0;
    int y = 0;

    private PixelMapHolder pixelMapHolder;

    public MainAbility() {
        e_surfaceView = null;
        e_videoSurfaceProvider = null;
        e_canvas = null;
        e_thread = null;
        e_running = false;
        e_paused = false;
        e_paintDraw = null;
        e_pauseCount = 0;
        e_paintFont = null;
        e_numPoints = 0;
        e_prefferredFrameRate = 40;
        e_sleepTime = 1000 / e_prefferredFrameRate;
        canvas = null;
        e_touchModesAble = true;
        e_touchNum = 5;
        e_isFrameOpen = true;
        e_touch_Mode = TouchMode.SINGLE;
        e_backgroundColor = Color.BLACK.getValue();
        e_sprite_group = new CopyOnWriteArrayList<>();
        e_spirte_recycle_group = new CopyOnWriteArrayList<>();
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        init();

        // init surfaceView
        e_surfaceView = new SurfaceProvider(this);
        e_videoSurfaceProvider = new SurfaceProvider(this);
        e_videoSurfaceProvider.getSurfaceOps().get().addCallback(new SurfaceOps.Callback() {
            @Override
            public void surfaceCreated(SurfaceOps surfaceOps) {
                if (e_videoSurfaceProvider.getSurfaceOps().isPresent()) {
                    player.setLooping(true);
                    player.setVideoSurface(e_videoSurfaceProvider.getSurfaceOps().get().getSurface());
                    e_videoSurfaceProvider.setTop(0);
                    player.play();
                }
            }

            @Override
            public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(SurfaceOps surfaceOps) {

            }
        });
        e_videoSurfaceProvider.pinToZTop(true);
        e_videoSurfaceProvider.setVisibility(Component.HIDE);
        e_surfaceViewLayout = (DependentLayout) findComponentById(ResourceTable.Id_dependentLayout);

        e_surfaceViewLayout.addComponent(e_surfaceView);
        e_surfaceViewLayout.addComponent(e_videoSurfaceProvider);

        // touch listener
        e_surfaceView.setTouchEventListener(this);

        // init touch mode
        if (e_touchModesAble) {
            e_touchPoints = new Point[e_touchNum];
            for (int i = 0; i < e_touchNum; i++) {
                e_touchPoints[i] = new Point(0, 0);
            }
        }

        // draw paint
        e_paintDraw = new Paint();
        e_paintDraw.setColor(Color.WHITE);
        // font paint
        e_paintFont = new Paint();
        e_paintFont.setColor(Color.WHITE);
        e_paintFont.setTextSize(24);

        load();

        // init thread
        e_running = true;
        e_thread = new Thread(this);
        e_thread.start();
    }

    @Override
    public void onActive() {
        super.onActive();
        e_paused = false;
        // need add...
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        e_paused = true;
        e_pauseCount++;
        // need add...
    }

    @Override
    public void run() {
        GameTimer frameTimer = new GameTimer();
        int frameCount = 0;
        int frameRate = 0;
        long startTime;
        long timeDiff;
        while (e_running) {
            if (e_paused) continue;

            frameCount++;
            startTime = frameTimer.getElapsed();

            // frame rate
            if (frameTimer.stopWatch(1000)) {

                frameRate = frameCount;

                frameCount = 0;

                // reset points
                e_numPoints = 0;
            }

            // update
            update();

            for (BaseSub A : e_sprite_group) {
                if (!A.getAlive()) continue;

                if (!A.isCollidable()) continue;

                if (A.isCollided()) continue;

                for (BaseSub B : e_sprite_group) {
                    if (!B.getAlive()) continue;

                    if (!B.isCollidable()) continue;

                    if (B.isCollided()) continue;

                    if (A == B) continue;

                    if (A.getIdentifier() ==
                            B.getIdentifier())
                        continue;

                    if (collisionCheck(A, B)) {
                        A.setCollided(true);
                        A.setOffender(B);
                        B.setCollided(true);
                        B.setOffender(A);
                        break;
                    }
                }
            }

            // lock canvas
            if (beginDrawing()) {
                draw();

                for (BaseSub baseSub : e_sprite_group) {
                    if (baseSub.getAlive()) {
                        baseSub.animation();
                        baseSub.draw();
                    }
                    if (baseSub.isCollidable() && baseSub.isCollided()) {
                        e_paintDraw.setColor(Color.RED);
                        e_paintDraw.setStyle(Paint.Style.STROKE_STYLE);
                        e_canvas.drawRect(baseSub.getBounds(), e_paintDraw);
                    }
                }

                // unlock the canvas
                endDrawing();
            }

            // new collision
            for (BaseSub baseSub : e_sprite_group) {
                if (!baseSub.getAlive()) {
                    e_spirte_recycle_group.add(baseSub);
                    e_sprite_group.remove(baseSub);
                    continue;
                }

                if (baseSub.isCollidable()) {
                    if (baseSub.isCollided()) {
                        if (baseSub.getOffender() != null) {
                            // collision
                            collision(baseSub);
                            // reset offender
                            baseSub.setOffender(null);
                        }
                        baseSub.setCollided(false);
                    }
                }

                baseSub.setCollided(false);
            }

            List<PaintView> paintViews = new ArrayList<>(PaintView.paintViewList);
            final int finalFrameRate = frameRate;

            getUITaskDispatcher().asyncDispatch(() -> e_surfaceView.addDrawTask((component, canvas) -> {
                for (PaintView paintView : paintViews) {
                    canvas.drawPixelMapHolderRect(paintView.holder, paintView.rectSrc, paintView.rectDst, paintView.paint);
                }
                if (e_isFrameOpen) {
                    int x = UIdefaultData.screenWidth - 150;
                    canvas.drawText(e_paintFont, "engine", x, 20);
                    canvas.drawText(e_paintFont, toString(finalFrameRate) + "fps", x, 40);
                    canvas.drawText(e_paintFont, "pauses:" + toString(e_pauseCount), x, 60);
                }
            }));
            // lock frame
            timeDiff = frameTimer.getElapsed() - startTime;
            long updatePeriod = e_sleepTime - timeDiff;
            if (updatePeriod > 0) {
                try {
                    Thread.sleep(updatePeriod);
                } catch (InterruptedException e) {
                    HiLog.error(label, "engine run start error:" + e);
                }
            }
        }

    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        if (e_touch_Mode == TouchMode.SINGLE) {
            touch(event);
        } else if (e_touch_Mode == TouchMode.FULL) {
            e_numPoints = event.getPointerCount();
            if (e_numPoints > e_touchNum) {
                e_numPoints = e_touchNum;
            }

            for (int n = 0; n < e_numPoints; n++) {
                e_touchPoints[n] = new Point(event.getPointerPosition(n).getX(), event.getPointerPosition(n).getY());
            }
        }
        return true;
    }

    /**
     * begin draw
     *
     * @return
     */
    private boolean beginDrawing() {
        e_canvas = e_surfaceView.getSurfaceOps().get().lockCanvas();
        return true;
    }

    /**
     * end draw
     */
    private void endDrawing() {
        e_surfaceView.getSurfaceOps().get().unlockCanvasAndPost(e_canvas);
    }

    /**
     * open frame count
     *
     * @param e_isFrameOpen
     */
    public void setIsFrameOpen(boolean e_isFrameOpen) {
        this.e_isFrameOpen = e_isFrameOpen;
    }

    /**
     * background color
     *
     * @param e_backgroundColor
     */
    public void setBackgroundColor(int e_backgroundColor) {
        this.e_backgroundColor = e_backgroundColor;
    }

    /**
     * set touch number
     *
     * @param e_touchNum
     */
    public void setTouchNum(int e_touchNum) {
        this.e_touchNum = e_touchNum;
    }

    /**
     * set touch mode able
     *
     * @param e_touchModesAble
     */
    public void setTouchModesAble(boolean e_touchModesAble) {
        this.e_touchModesAble = e_touchModesAble;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {

    }

    public enum ScreenMode {
        LANDSCAPE(AbilityInfo.DisplayOrientation.LANDSCAPE),
        PORTRAIT(AbilityInfo.DisplayOrientation.PORTRAIT);
        public AbilityInfo.DisplayOrientation value;

        ScreenMode(AbilityInfo.DisplayOrientation mode) {
            this.value = mode;
        }
    }

    /**
     * set screenOrientation
     *
     * @param mode
     */
    public void setScreenOrientation(Engine.ScreenMode mode) {
        setDisplayOrientation(mode.value);
    }

    /**
     * shortcut method to duplicate existing  Ohos methods
     *
     * @param msg
     */
    public void fatalError(String msg) {
        System.exit(0);
    }

    /**
     * draw helper
     */

    /**
     * draw text
     *
     * @param text
     * @param x
     * @param y
     */
    public void drawText(String text, int x, int y) {
        e_canvas.drawText(e_paintFont, text, x, y);
    }

    /**
     * engine helper
     */

    /**
     * @return surface
     */
    public SurfaceProvider getSurfaceView() {
        return e_surfaceView;
    }

    /**
     * @return canvas
     */
    public Canvas getCanvas() {
        return e_canvas;
    }

    /**
     * @return canvas
     */
    public SurfaceProvider getSurfaceProvider() {
        return e_surfaceView;
    }

    @Override
    public void debugDraw(RectFloat bound) {

    }

    /**
     * set frame rete
     *
     * @param rate
     */
    public void setFrameRate(int rate) {
        e_prefferredFrameRate = rate;
        e_sleepTime = 1000 / e_prefferredFrameRate;
    }

    /**
     * get touch puts
     *
     * @return
     */
    public int getTouchPoints() {
        return e_numPoints;
    }

    /**
     * get touch point
     *
     * @param n
     * @return
     */
    public Point getTouchPoint(int n) {
        if (n < 0) {
            n = 0;
        }
        if (n > e_touchNum) {
            n = e_touchNum;
        }
        return e_touchPoints[n];
    }

    /**
     * set paint color
     *
     * @param color
     */
    public void setDrawColor(int color) {
        e_paintDraw.setColor(new Color(color));
    }

    /**
     * set text color
     *
     * @param color
     */
    public void setTextColor(int color) {
        e_paintFont.setColor(new Color(color));
    }

    /**
     * set text size
     *
     * @param size
     */
    public void setTextSize(int size) {
        e_paintFont.setTextSize(size);
    }

    public void setTextSize(float size) {
        e_paintFont.setTextSize((int) size);
    }

    public enum FontStyles {
        NORMAL(Font.DEFAULT),
        BOLD(Font.DEFAULT_BOLD),
        ITALIC(new Font.Builder("italic").makeItalic(true).build()),
        BOLD_ITALIC(new Font.Builder("bold_italic").makeItalic(true).setWeight(Font.BOLD).build());
        Font value;

        FontStyles(Font value) {
            this.value = value;
        }
    }

    /**
     * set type face
     *
     * @param style
     */
    public void setFontStyle(FontStyles style) {
        e_paintFont.setFont(style.value);
    }

    /**
     * double round
     *
     * @param value
     * @return
     */
    public double round(double value) {
        return round(value, 2);
    }

    private double round(double value, int precision) {
        try {
            BigDecimal bd = new BigDecimal(value);
            BigDecimal rounded = bd.setScale(precision, BigDecimal.ROUND_HALF_UP);
            return rounded.doubleValue();
        } catch (Exception e) {
            HiLog.error(label, "engine" + " round error:" + e);
        }
        HiLog.error(label, "engine" + " round D:" + 0);
        return 0;
    }

    private boolean collisionCheck(BaseSub A, BaseSub B) {
        return RectFloat.isIntersect(A.getBounds(), B.getBounds());
    }

    /**
     * to string
     *
     * @param value
     * @return
     */
    public String toString(int value) {
        return Integer.toString(value);
    }

    public String toString(float value) {
        return Float.toString(value);
    }

    public String toString(double value) {
        return Double.toString(value);
    }

    public String toString(Float2 value) {
        return "X:" + round(value.x) + "," + "Y:" + round(value.y);
    }

    public String toString(Float3 value) {
        return "X:" + round(value.x) + "," + "Y:" + round(value.y)
                + "Z:" + round(value.z);
    }

    public String toString(Rect value) {
        RectFloat rectF = new RectFloat(value.left, value.top, value.right, value.bottom);
        return toString(rectF);
    }

    public String toString(RectFloat value) {
        return "{" + round(value.left) + "," +
                round(value.top) + "," +
                round(value.right) + "," +
                round(value.bottom) + "}";
    }

    /**
     * add BaseSub to group
     *
     * @param sprite
     */
    protected void addToSpriteGroup(BaseSub sprite) {
        e_sprite_group.add(sprite);
    }

    /**
     * remove from group
     *
     * @param sprite
     */
    protected void removeFromSpriteGroup(BaseSub sprite) {
        e_sprite_group.remove(sprite);
    }

    protected void removeFromSpriteGroup(int index) {
        e_sprite_group.remove(index);
    }

    /**
     * get size
     *
     * @return size
     */
    protected int getSpriteGroupSize() {
        return e_sprite_group.size();
    }

    protected int getRecycleGroupSize() {
        return e_spirte_recycle_group.size();
    }

    protected void addToRecycleGroup(BaseSub baseSub) {
        e_spirte_recycle_group.add(baseSub);
    }

    protected void removeFromRecycleGroup(int index) {
        e_spirte_recycle_group.remove(index);
    }

    protected void removeFromRecycleGroup(BaseSub baseSub) {
        e_spirte_recycle_group.remove(baseSub);
    }

    protected boolean isRecycleGroupEmpty() {
        return e_spirte_recycle_group.isEmpty();
    }

    protected BaseSub recycleSubFromGroup(int id) {
        for (BaseSub baseSub : e_spirte_recycle_group) {
            if (baseSub.getIdentifier() == id) {
                return baseSub;
            }
        }
        return null;
    }

    protected int getTypeSizeFromRecycleGroup(int id) {
        int num = 0;
        for (BaseSub baseSub : e_spirte_recycle_group) {
            if (baseSub.getIdentifier() == id) {
                num++;
            }
        }
        HiLog.error(label, "engine" + "num" + num, "id" + id);
        return num;
    }


    public void init() {
        player = new MusicPlayer(this, "resources/rawfile/test.mp4");
        paint = new Paint();
        printer = new GameTextPrinter();
        printer.setTextColor(Color.BLACK.getValue());
        printer.setTextSize(24);
        printer.setLineSpaceing(28);
        shoottimer = new GameTimer();
        timer = new GameTimer();
        random = new Random();
        enemyTimer = new GameTimer();
        bg_scroll = new Point(0, 0);
        setScreenOrientation(Engine.ScreenMode.PORTRAIT);
        UIdefaultData.init(this);
    }


    public void load() {
        try {
            // load ship
            GameTexture texture1 = new GameTexture(this);
            texture1.loadFromAsset("resources/base/graphic/shoot.png");
            ship = new BaseSprite(this, 100, 124, FrameType.COMMON);
            ship.setTexture(texture1);
            ship.addRectFrame(0, 100, 100, 124);
            ship.addRectFrame(165, 361, 100, 124);
            ship.addAnimation(new FrameAnimation(0, 1, 1));
            ship.setPosition(UIdefaultData.centerInHorizontalX - ship.getWidthWithScale() / 2,
                    UIdefaultData.screenHeight + ship.getHeightWidthScale());
            ship.setDipScale(96, 96);
            ship.addfixedAnimation("start",
                    new MoveAnimation(UIdefaultData.centerInHorizontalX - ship.getWidthWithScale() / 2,
                            UIdefaultData.screenHeight - 2 * ship.getHeightWidthScale(), new Float2(10, 10)));
            ship.setName("SHIP");
            ship.setIdentifier(SHIP);
            addToSpriteGroup(ship);

            // load bg
            GameTexture tex = new GameTexture(this);
            if (!tex.loadFromAsset("resources/base/graphic/background.png")) {
                fatalError("Error loading space");
            }

            pixelMapHolder = new PixelMapHolder(tex.getBitmap());
            bg_src = new RectFloat(0, 0, 480, 800);
            bg_dst = new RectFloat(0, 0, UIdefaultData.screenWidth, UIdefaultData.screenHeight);
            PaintView.paintViewList.add(new PaintView(pixelMapHolder, bg_src, bg_dst, e_paintDraw));

            shoot = new GameTexture(this);
            shoot.loadFromAsset("resources/base/graphic/flare.png");

            enemyPic = new GameTexture(this);
            enemyPic.loadFromAsset("resources/base/graphic/enemy.png");

            bg_scroll = new Point(0, 0);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    public void draw() {
        PaintView.paintViewList.clear();
        PaintView.paintViewList.add(new PaintView(pixelMapHolder, bg_src, bg_dst, e_paintDraw));
    }


    public void update() {
        if (timer.stopWatch(20)) {
            scrollBackground();
        }
        if (ship.getFixedAnimation("start").animating) {
            ship.fixedAnimation("start");
        } else {
            fireBullet();
            int size = getTypeSizeFromRecycleGroup(ENEMY);
            if (size > 0)
                enemyNum -= size;
            if (enemyTimer.stopWatch(200)) {
                addEnemy();
            }
        }
    }

    public void collision(BaseSub baseSub) {
        BaseSprite other = (BaseSprite) baseSub.getOffender();
        if (baseSub.getIdentifier() == BULLET &&
                other.getIdentifier() == ENEMY) {

            // 短音效 碰撞爆炸音效
            SoundManager manager = new SoundManager(this, 5);
            manager.addSound("resource/rawfile/town.mid");
            manager.play("resource/rawfile/town.mid");

            other.setAlive(false);
            removeFromSpriteGroup(other);
            addToRecycleGroup(other);
            enemyNum--;

            manager.removeSound("resource/rawfile/town.mid");
        }
    }

    public void touch(TouchEvent event) {
        MmiPoint mmiPoint = event.getPointerPosition(event.getIndex());
        switch (event.getAction()) {
            case TouchEvent.POINT_MOVE:
                if(firstKeyDown) {
                    startX = (int) mmiPoint.getX();
                    startY = (int) mmiPoint.getY();
                    firstKeyDown = false;
                    break;
                }
                offsetX = mmiPoint.getX() - startX;
                offsetY = mmiPoint.getY() - startY;
                if (Math.abs(offsetX) > Math.abs(offsetY)) {
                    if (ship.s_position.x + offsetX > 0
                            && ship.s_position.x + offsetX +
                            ship.getHeightWidthScale() < UIdefaultData.screenWidth) {
                        ship.s_position.x += offsetX;
                        resetEvent(event);
                    }
                } else {
                    if (ship.s_position.y + offsetY > 0
                            && ship.s_position.y + offsetY +
                            ship.getHeightWidthScale() < UIdefaultData.screenHeight) {
                        ship.s_position.y += offsetY;
                        resetEvent(event);
                    }
                }
                break;
            case TouchEvent.PRIMARY_POINT_DOWN:
                firstKeyDown = true;
                break;
        }
    }

    public void scrollBackground() {
        int y = bg_scroll.getPointYToInt();
        y += 10.0f;
        bg_scroll.modify(bg_scroll.getPointX(), y);
        bg_dst.top = bg_scroll.getPointY();
        bg_dst.bottom = bg_dst.top + UIdefaultData.screenHeight - 1;
        if (bg_scroll.getPointY() + bg_dst.getHeight() > UIdefaultData.screenHeight * 2) {
            bg_scroll.modify(bg_scroll.getPointX(), (bg_scroll.getPointY() - bg_dst.getHeight()));
        }
    }

    public void fireBullet() {
        if (!shoottimer.stopWatch(300)) return;
        BaseSprite bullet;
        if (getTypeSizeFromRecycleGroup(BULLET) > 0) {
            bullet = (BaseSprite) recycleSubFromGroup(BULLET);
            bullet.clearAllAnimation();
            removeFromRecycleGroup(bullet);
        } else {
            bullet = new BaseSprite(this);
            bullet.setTexture(shoot);
            bullet.setDipScale(8, 18);
            bullet.setIdentifier(BULLET);
        }
        double angle = 270.0;
        float speed = 20.0f;
        int lifetime = 2500;
        bullet.addAnimation(new VelocityAnimation(angle, speed,
                lifetime));
        bullet.setPosition(ship.s_position.x +
                        ship.getWidthWithScale() / 2
                        - bullet.getWidthWithScale() / 2
                        - bullet.getWidth() / 2,
                ship.s_position.y - ship.getHeight() / 2);
        bullet.setAlive(true);
        addToSpriteGroup(bullet);
    }

    private void resetEvent(TouchEvent event) {
        MmiPoint mmiPoint = event.getPointerPosition(event.getIndex());
        startX = (int) mmiPoint.getX();
        startY = (int) mmiPoint.getY();
    }

    private void addEnemy() {
        BaseSprite enemy;
        if (getTypeSizeFromRecycleGroup(ENEMY) > 0) {
            enemy = (BaseSprite) recycleSubFromGroup(ENEMY);
            enemy.clearAllAnimation();
            removeFromRecycleGroup(enemy);
        } else {
            enemy = new BaseSprite(this);
            enemy.setTexture(enemyPic);
            enemy.setIdentifier(ENEMY);
            enemy.setDipScale(49, 36);
        }
        double angle = 90.0;
        float speed = 5.0f;
        int lifetime = 5000;
        enemy.addAnimation(new VelocityAnimation(angle, speed,
                lifetime));
        enemy.setPosition(random.nextInt(UIdefaultData.screenWidth),
                -enemy.getWidthWithScale());
        enemy.setAlive(true);
        addToSpriteGroup(enemy);
        enemyNum++;
    }
}